<template>
  <view class="article-box">
    <u-form :model="form" ref="uForm">
      <u-form-item label="类型">
        <u-radio-group v-model="form.radioValue">
          <u-radio
            v-for="(item, index) in list"
            :key="index"
            :name="item.id"
            :disabled="item.disabled"
          >
            {{ item.name }}
          </u-radio>
        </u-radio-group>
      </u-form-item>
      <u-form-item label="标题" prop="title">
        <u-input v-model="form.title" />
      </u-form-item>
      <u-form-item label="内容" prop="content">
        <view style="text-align: right; width: 100%">
          <u-button size="mini" type="primary" @click="getEditor">
            edit
          </u-button>
        </view>
      </u-form-item>
    </u-form>
    <u-button type="primary" @click="PublishArticles"> 发布文章 </u-button>
  </view>
</template>

<script>
import { PublishArticlesUrl } from "@/api/article.js";
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      form: {
        radioValue: "dev",
        title: "",
      },
      list: [
        { name: "分享", id: "ask" },
        { name: "问答", id: "share" },
        { name: "招聘", id: "job" },
        { name: "测试", id: "dev" },
      ],
      rules: {
        title: [
          {
            required: true,
            message: "请输入标题",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            min: 3,
            message: "标题不能少于3个字",
            trigger: "change",
          },
        ],
        content: [
          {
            validator: () => {
              if (!this.editorStr.trim()) {
                return false;
              }
              return true;
            },
            message: "请输入内容",
          },
        ],
      },
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  computed: {
    ...mapState("editor", ["editorStr"]),
  },
  methods: {
    ...mapActions("editor", ["editorStr_action"]),
    getEditor() {
      uni.navigateTo({ url: "/pages/editor/index" });
    },
    PublishArticles() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          let param = {
            title: this.form.title,
            tab: this.form.radioValue,
            content: JSON.stringify(this.editorStr),
          };
          PublishArticlesUrl(param).then((res) => {
            if (res.success) {
              uni.showToast({
                icon: "success",
                title: "发布成功",
                duration: 2000,
              });
              setTimeout(() => {
                console.log(uni.redirectTo);
                uni.switchTab({ url: "/pages/home/index" });
              }, 2000);
            }
          });
        } else {
          console.log("验证失败");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.article-box {
  padding: 20rpx 40rpx;
}
.radio-box {
  text-align: center;
}
</style>